<template>
  <div class="app-container">
    <div class="filter-container" style="padding-bottom: 20px;">
      <el-select @keyup.enter.native="handleFilter" @change='handleFilter' v-model="listQuery.opuser" filterable remote reserve-keyword
        placeholder="请输入管理员名" :remote-method="querySearchAsync" :loading="loading" v-if="['log', 'admin'].indexOf(type) !== -1">
        <el-option
          v-for="item in opnames"
          :key="item._id"
          :label="item.username"
          :value="item._id">
        </el-option>
      </el-select>
      <el-select @change='handleFilter' placeholder="应用" style="width: 140px" class="filter-item" v-model="listQuery.appid" v-if="['login', 'push', 'api'].indexOf(type) !== -1">
        <el-option v-for="(val, key) in apps" :key="key" :label="val" :value="key">
        </el-option>
      </el-select>
      <el-select @change='handleFilter' placeholder="状态码" style="width: 140px" class="filter-item" v-model="listQuery.code" v-if="['push', 'api'].indexOf(type) !== -1">
        <el-option v-for="(val, key) in returns" :key="val" :label="val" :value="val">
        </el-option>
      </el-select>
      <el-select @change='handleFilter' placeholder="操作类型" style="width: 140px" class="filter-item" v-model="listQuery.optype" v-if="type === 'push'">
        <el-option v-for="(val, key) in logTypePush" :key="key" :label="val" :value="key">
        </el-option>
      </el-select>
      <el-select @change='handleFilter' placeholder="操作类型" style="width: 140px" class="filter-item" v-model="listQuery.optype" v-if="type === 'api'">
        <el-option v-for="(val, key) in logTypeApi" :key="key" :label="val" :value="key">
        </el-option>
      </el-select>
      <el-date-picker
        v-model="listQuery.optimeStart"
        value-format="yyyy-MM-dd"
        align="right"
        type="date"
        placeholder="开始日期"
        :picker-options="pickerOptions1">
      </el-date-picker>
      <el-date-picker
        v-model="listQuery.optimeEnd"
        value-format="yyyy-MM-dd"
        align="right"
        type="date"
        placeholder="结束日期"
        :picker-options="pickerOptions1">
      </el-date-picker>
      <el-button class="filter-item" type="primary" icon="el-icon-reset" @click="handleReset">重置</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
    </div>
    <el-table :data="data.list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column type="index" label="序号" width="50">
      </el-table-column>
      <el-table-column label="管理员" v-if="['login', 'admin'].indexOf(type) !== -1">
        <template slot-scope="scope">
          {{scope.row.opname}}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="应用名称"  width="120" v-if="['push', 'api', 'test'].indexOf(type) !== -1">
        <template slot-scope="scope">
          <span>{{scope.row.appname}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" width="200" label="操作时间">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{scope.row.optime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="IP地址" width="160" v-if="type !== 'push'">
        <template slot-scope="scope">
          <span>{{scope.row.ip}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="设备信息" v-if="type === 'login'">
        <template slot-scope="scope">
          <span>{{getAgent(scope.row.agent)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作名称" width="180" v-if="['admin', 'push', 'api', 'test'].indexOf(type) !== -1">
        <template slot-scope="scope">
          <span>{{logTypes[scope.row.optype] || scope.row.optype}}</span>
        </template>
      </el-table-column>
      <el-table-column label="查询字符串" v-if="['admin', 'test'].indexOf(type) !== -1">
        <template slot-scope="scope">
          <span :title="JSON.stringify(scope.row.g)" style="color: blue;">{{(JSON.stringify(scope.row.g) || '').substr(0, 30)}}</span>
          <span :title="JSON.stringify(scope.row.p)" style="color: green;">{{(JSON.stringify(scope.row.p) || '').substr(0, 30)}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="type === 'login' ? '登录结果' : '备注'">
        <template slot-scope="scope">
          <span :title="scope.row.get">{{scope.row.mark}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" width="80" label="返回码" align="center" v-if="['push', 'api', 'test'].indexOf(type) !== -1">
        <template slot-scope="scope">
          <el-tag :type="scope.row.code | statusFilter" :title="scope.row.hs + 'ms'">{{scope.row.code}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="接口耗时" width="80">
        <template slot-scope="scope">
          <span :style="{color: ttlColor(scope.row.hs)}">{{scope.row.hs}}ms</span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top:30px;"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="data.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="data.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.total">
    </el-pagination>

  </div>

</template>

<script>
/*global UAParser*/
import { getList } from '@/api/log'
import { getList as getAdminList } from '@/api/admin'
import { getOpt } from '@/api/app'
import { logType, logCodes, logTypeApi, logTypePush } from '@/utils/auth'

export default {
  data() {
    return {
      data: {
        limit: 10,
        total: 0,
        page: 1
      },
      opnames: [],
      logTypes: Object.assign({}, logType, logTypeApi, logTypePush, logCodes),
      logType: logType,
      logTypeApi: logTypeApi,
      logTypePush: logTypePush,
      apps: {},
      returns: [200, 301, 302, 404, 501, 502],
      listQuery: {},
      listSelect: [],
      opts: {
        status: [
          {
            key: '', label: '全部'
          },
          {
            key: true, label: '正常'
          },
          {
            key: false, label: '冻结'
          }
        ]
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      listLoading: true,
      loading: false
    }
  },
  filters: {
    statusFilter(code) {
      const statusMap = { 200: 'success', 301: 'gray', 302: 'gray', 404: 'danger', 501: 'danger', 502: 'danger' }
      return statusMap[code]
    }
  },
  created() {
    this.apps = {}
    this.type = this.$route.path.replace('/log/', '')
    var opuser = this.$route.query.opuser
    if (opuser) {
      this.opnames = [{ _id: opuser, username: this.$route.query.opname || '' }]
      this.listQuery.opuser = opuser
    }
    this.fetchData()
    getOpt(opt => {
      this.apps = opt
    })
  },
  methods: {
    ttlColor(ttl) {
      if (ttl > 1000) return 'red'
      if (ttl <= 100) return 'green'
      if (ttl > 100 && ttl <= 400) return 'orange'
      if (ttl > 400 && ttl <= 1000) return 'brown'
    },
    querySearchAsync(queryString, cb) {
      getAdminList({ username: queryString }).then(res => {
        this.opnames = res.data.list
      })
    },
    handleSelect(item) {
      this.fetchData()
    },
    getAgent(agent) {
      var parser = new UAParser(agent)
      var rs = parser.getResult()
      return [rs.device.model, rs.os.name, rs.os.version].join(' ')
    },
    handleReset() {
      this.optime = []
      this.listQuery = {}
      this.$forceUpdate()
      this.fetchData()
    },
    handleSelectionChange(val) {
      this.listSelect = val
    },
    handleFilter() {
      if (!this.listQuery.optimeStart) delete this.listQuery.optimeStart
      if (!this.listQuery.optimeEnd) delete this.listQuery.optimeEnd
      if (this.listQuery.opuser === '') delete this.listQuery.opuser
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    fetchData(con) {
      this.listLoading = true
      getList(this.type, this.listQuery).then(response => {
        for (var i in response.data) {
          this[i] = response.data[i]
        }
        this.data = response.data
        this.listLoading = false
      })
    }
  }
}
</script>
